from django.db.models import Sum
from django.shortcuts import render,redirect,HttpResponse
from firstplan.mine import myform
from firstplan import models


def reward(request):
    title = "显示累积奖励"
    queryset1 = models.Person.objects.values("id")
    print("queryset1: ", queryset1)
    queryset = models.Reward.objects.values("person").annotate(reward=Sum("reward"))
    print("queryset: ", queryset)
    if queryset:
        for item in queryset:
            item['id'] = item['person']
            print("reward1: ", item["reward"])
        return render(request,'reward.html',{"title":title,'queryset':queryset})
    queryset = queryset1
    print("queryset-1", queryset)
    for item in queryset:
        item["reward"] = 0
        print("reward: ",item["reward"])
    return render(request, 'reward.html', {"title": title, 'queryset': queryset})


def reward_detail(request,person):
    title="显示奖励明细"
    if person:
        queryset = models.Reward.objects.filter(person=person)
        return render(request, 'reward_detail.html', {"title": title, 'queryset': queryset})
    return redirect('/reward/')


def reward_list(request):
    title = "显示奖励列表"
    queryset = models.Reward.objects.all()
    return render(request, 'reward_list.html', {"title": title, 'queryset': queryset})


def reward_edit(request,uid):
    title = "修改奖励"
    queryset = models.Reward.objects.filter(id=uid).first()
    if request.method == 'GET':
        form = myform.RewardForm(instance=queryset)
        return render(request, 'add_or_edit.html', {"title": title, 'form': form})
    form = myform.RewardForm(data=request.POST,instance=queryset)
    if form.is_valid():
        exists = models.Reward.objects.filter(person=form.cleaned_data['person'],date=form.cleaned_data['date']).exists()
        if not exists:
            form.save()
            return redirect('/reward/list/')
        else:
            return HttpResponse("数据已存在")
    return render(request, 'add_or_edit.html', {"title": title, 'form': form})


def reward_delete(request,uid):
    title = "删除奖励"
    models.Reward.objects.filter(id=uid).delete()
    return redirect('/reward/list/')


def reward_add(request):
    title = "添加奖励"
    if request.method == 'GET':
        form = myform.RewardForm()
        return render(request, 'add_or_edit.html', {"title": title, 'form': form})
    form = myform.RewardForm(data=request.POST)
    if form.is_valid():
        print(form.cleaned_data)
        # date = form.cleaned_data['date']
        # end_date = date + timedelta(days=6)
        # person = form.cleaned_data['person']
        # reward = form.cleaned_date['reward']
        # print(date,end_date,person,reward)
        form.save()
        return redirect('/reward/list/')
    return render(request, 'add_or_edit.html', {"title": title, 'form': form})